'''
Author: 风云 mayude@live.cn
Date: 2022-10-24 22:20:04
LastEditors: 风云 mayude@live.cn
LastEditTime: 2022-10-24 22:20:33
FilePath: /tinyms/tinyms-api/apps/chat/server.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from pywss import Pyws, route, json, ConnectManager

@route('/ws/chat')
def ws_chat(request, data):
    json_data = json.loads(data)
    if json_data.get('start') == True:  # 接收start指令
        # 更新全部已创建链接的socket - 当前在线人数
        request.conn.send_to_all({'online': ConnectManager.online()})
        return {'sock_id': request.conn.name}  # 返回自身惟一sock_id
    msg = json_data.get('msg')
    if msg:  # 获取聊天消息，发送给全部已创建链接的socket
        request.conn.send_to_all({'from': request.conn.name, 'msg': msg})

if __name__ == '__main__':
    ws = Pyws(__name__, address='127.0.0.1', port=8868)
    ws.serve_forever()